package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.domain.Category;
import com.itheima.domain.R;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //添加分类菜品套餐
    @PostMapping
    public R save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("分类添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R select(Integer page,Integer pageSize){
        IPage<Category> iPage = new Page<>(page,pageSize);
        //进行分页排序
        LambdaQueryWrapper<Category> wapper = new LambdaQueryWrapper<>();
        //排序条件sort
        wapper.orderByAsc(Category::getSort);
        IPage<Category> categoryIPage = categoryService.page(iPage,wapper);
        return R.success(categoryIPage);
    }

    //删除菜品功能
    @DeleteMapping
    public R delete(Long id){
        LambdaQueryWrapper<Category> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Category::getId,id);
        Category one = categoryService.getOne(wapper);
        if(one==null){
            return R.error("菜品删除失败");
        }
        categoryService.remove(id);
        return R.success("菜品删除成功");
    }

    //修改菜品功能
    @PutMapping
    public R update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //菜品新增  回显
    @GetMapping("/list")
    public R save(Integer type){
        LambdaQueryWrapper<Category> wapper = new LambdaQueryWrapper<>();
        if(type!=null){
            wapper.eq(Category::getType,type);
        }
        List<Category> list = categoryService.list(wapper);
        return R.success(list);
    }
}
